package com.kalman.taobao.module.screen;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.service.requestcontext.buffered.BufferedRequestContext;
import com.alibaba.citrus.service.uribroker.URIBrokerService;
import com.alibaba.citrus.service.uribroker.uri.ServletContentURIBroker;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.turbine.dataresolver.Param;
import com.kalman.biz.common.HnrResourceLoader;
import com.kalman.biz.result.Result;
import com.kalman.biz.taobao.ao.ICouponsAo;
import com.kalman.common.CalendarUtil;
import com.kalman.common.auth.DES;
import com.kalman.dao.pojo.TaobaoCouponsDO;
import com.kalman.taobao.CouponsReason;
import com.kalman.webx.UserTrackInfo;

/**
 * 
 * @author kalman03
 */
public class Coupons {

	private final static Logger log = LoggerFactory.getLogger(Coupons.class);
	@Autowired
	private HttpServletResponse response;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private BufferedRequestContext brc;
	@Autowired
	private URIBrokerService uriBrokerService;
	@Autowired
	private ICouponsAo couponsAo;
	
	@SuppressWarnings("unchecked")
	public void execute(@Param(name="sign",defaultValue="")String sign,
			Navigator navigator,
			Context context) throws Exception {
		if(! isRightSign(sign)){
			navigator.redirectToLocation("http://www.ihunanren.com/portal.php?mod=topic&topicid=6");
			return;
		}
		if(isObtainOutOfTimes()){
			navigator.forwardTo("couponsNav").withParameter("reason", ""+CouponsReason.obtain_out_of_times.getKey());
			return;
		}
		
		// 必须关闭buffering，未完成的页面才会被显示在浏览器上。
		brc.setBuffering(false);

		// 设置content type，但不需要设置charset，框架会设置正确的charset。
		response.setContentType("text/html");

		ServletContentURIBroker broker = (ServletContentURIBroker) uriBrokerService.getURIBroker("taobaoAssetsContent");
		String taobaoAssetsPath = broker.getServerURI();
		
		PrintWriter out = response.getWriter();
		
		out.println(getHeader(taobaoAssetsPath));
		out.flush();
		Thread.sleep(2000);
		
		Result result = couponsAo.getCouponUrls(100);
		if(result.isSuccess()){
			List<TaobaoCouponsDO> list = (List<TaobaoCouponsDO>) result.getDefaultModel();
			
			int count = 1;
			for(TaobaoCouponsDO couponsDO:list){
				if(count++ == 41){
					out.println(gteTips());
				}else{
					out.println(getBody(couponsDO));
				}
				out.flush();
				Thread.sleep(500);
			}
		}
		out.println(getFooter(taobaoAssetsPath));
		out.flush();
	}
	
	private String gteTips(){
		return "<li style='width:100%'><a href='http://ju.taobao.com'><img src='http://img.taobaocdn.com/imgextra/i1/431082987/T2gBHLXg4aXXXXXXXX_!!431082987.png' width='940' height='150'></a></li>";
	}
	
	/**领取次数是否达到上限*/
	private boolean isObtainOutOfTimes(){
		UserTrackInfo trackInfo = new UserTrackInfo(request);
		return couponsAo.isObtainOutOfTimes(trackInfo.getIpAddress());
	}
	
	/**两次间隔不能超过5分钟*/
	private boolean isRightSign(String sign){
		try {
			String time = DES.decrypt(sign, DES.DEFAULT_KEY);
			Date firstDate = new Date(Long.parseLong(time));
			return CalendarUtil.getTimeIntervalMins(firstDate, new Date())<=5;
		} catch (Exception e) {
			log.error("DES.decrypt catch a exception:"+e.getMessage());
			return false;
		}
	}

	private String getBody(TaobaoCouponsDO taobaoCouponsDO) throws IOException {
		return String.format(
				HnrResourceLoader.getResoureceAsString("tb_coupons_body.dat"),
				taobaoCouponsDO.getShopUrl(), taobaoCouponsDO.getNick(),
				taobaoCouponsDO.getShopLogo(), taobaoCouponsDO.getNick(),
				taobaoCouponsDO.getLink());
	}

	private String getHeader(String taobaoAssetsPath) throws IOException {
		return String.format(HnrResourceLoader.getResoureceAsString("tb_coupons_header.dat"),taobaoAssetsPath);
	}

	private String getFooter(String taobaoAssetsPath) throws IOException {
		return HnrResourceLoader.getResoureceAsString("tb_coupons_footer.dat");
	}
}
